package main

import (
	"bufio"
	"common"
	"common/log"
	"context"
	"errors"
	"euplink"
	"fmt"
	"github.com/spf13/cobra"
	"go.uber.org/zap"
	"os"
	"path"
	"strings"
	"time"
)

func parseM3u8File(fullPath string) ([]string, error) {

	f, err := os.Open(fullPath)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	s := bufio.NewScanner(f)
	files := make([]string, 0)
	for s.Scan() {
		line := s.Text()
		if strings.HasPrefix(line, "#") {
			continue
		}
		//file := path.Join(dir, line)
		files = append(files, line)
	}
	err = s.Err()
	fmt.Println(err)
	return files, nil
}

var uploadHlsCmd = &cobra.Command{
	Use:   "uploadhls",
	Short: "上传hls",
	Long:  "euplink uploadhls (local_src)",
	RunE:  cmdUploadHls,
}

func cmdUploadHls(cmd *cobra.Command, args []string) error {
	if len(args) != 1 {
		return errors.New("参数错误")
	}

	ctx := context.Background()
	var cancel context.CancelFunc
	ctx, cancel = context.WithCancel(ctx)
	defer cancel()
	zapLog := log.NewZapLog(&runConfig.Log)
	////runConfig.Project.LocalDeviceId = runConfig.LocalDeviceId
	//runConfig.Project.RootKey = rootKeyToMd5(runConfig.RootKey)
	//runConfig.Project.ApiKey = runConfig.ApiKey

	files, err := parseM3u8File(args[0])
	if err != nil {
		zapLog.Error("parseM3u8File failed", zap.Error(err))
		return nil
	}

	prj, err := euplink.NewProject(ctx, runConfig.Project, zapLog)
	if err != nil {
		return fmt.Errorf("project init err: %s", err)
	}
	prj.StartUpdateNodeServer(ctx)

	dir, _ := path.Split(args[0])
	var success, failed int
	var count = len(files)
	var tryCount = 0
	for i := 0; i < count; {
		var file = files[i]
		localFile := path.Join(dir, file)
		//fmt.Println("upload ", localFile, " to ", file)
		t1 := time.Now()
		ctx2 := context.Background()
		fp, size, err := common.OpenFile(localFile)
		if err != nil {
			failed++
			tryCount++
			zapLog.Error("上传失败", zap.String("file", file), zap.Error(err))
		} else {
			err = prj.UploadObject(ctx2, runConfig.Project.DefaultBucket, file, fp, false, size, nil)
			if err != nil {
				failed++
				tryCount++
				zapLog.Error("上传失败", zap.String("file", file), zap.Error(err))
				time.Sleep(time.Second * 3)
			} else {
				tryCount = 0
				i++
				success++
				zapLog.Info("上传成功", zap.String("file", file), zap.Duration("time", time.Now().Sub(t1)))
			}
		}
		zapLog.Info("统计:", zap.Int("failed", failed), zap.Int("success", success))
	}
	return nil
}
